package com.example.androidshixi;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class ChangePasswordActivity extends AppCompatActivity {

    private EditText oldPasswordEditText, newPasswordEditText, confirmPasswordEditText;
    private Button changePasswordButton;
    private DatabaseHelper databaseHelper;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);

        oldPasswordEditText = findViewById(R.id.old_password_edittext);
        newPasswordEditText = findViewById(R.id.new_password_edittext);
        confirmPasswordEditText = findViewById(R.id.confirm_password_edittext);
        changePasswordButton = findViewById(R.id.change_password_button);
        databaseHelper = new DatabaseHelper(this);

        // 获取传递过来的用户名
        username = getIntent().getStringExtra("username");

        changePasswordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPassword = oldPasswordEditText.getText().toString().trim();
                String newPassword = newPasswordEditText.getText().toString().trim();
                String confirmPassword = confirmPasswordEditText.getText().toString().trim();

                if (!TextUtils.isEmpty(oldPassword) &&!TextUtils.isEmpty(newPassword) &&!TextUtils.isEmpty(confirmPassword)) {
                    if (databaseHelper.validateUser(username, oldPassword)) {
                        if (newPassword.equals(confirmPassword)) {
                            boolean isUpdated = databaseHelper.updatePassword(username, newPassword);
                            if (isUpdated) {
                                Toast.makeText(ChangePasswordActivity.this, "密码修改成功", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toast.makeText(ChangePasswordActivity.this, "密码修改失败", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(ChangePasswordActivity.this, "新密码和确认密码不一致", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(ChangePasswordActivity.this, "旧密码不正确", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(ChangePasswordActivity.this, "请输入完整信息", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}